package com.zml.control.widget.widget;

import com.alibaba.fastjson.JSON;
import com.zml.control.ControlMainAbility;
import com.zml.control.entity.OcMqttEntity;
import com.zml.control.widget.controller.FormController;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.FormBindingData;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Form controller implementation.
 */
public class WidgetImpl extends FormController {
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, WidgetImpl.class.getName());
    private static final int DEFAULT_DIMENSION_2X2 = 2;

    public WidgetImpl(Context context, String formName, Integer dimension) {
        super(context, formName, dimension);
    }

    @Override
    public ProviderFormInfo bindFormData(long formId) {
        HiLog.info(TAG, "bind form data");
        ProviderFormInfo providerFormInfo = new ProviderFormInfo();
        if (dimension == DEFAULT_DIMENSION_2X2) {
            ZSONObject zsonObject = new ZSONObject();
            zsonObject.put("", "");
            providerFormInfo.setJsBindingData(new FormBindingData(zsonObject));
        }
        return providerFormInfo;
    }

    @Override
    public void updateFormData(long formId, Object... vars) {
        HiLog.info(TAG, "update form data: formId" + formId);
        // 获取华为云IotDA设备影子数据
        String url = "https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/0c2785b9a98010d52f9dc00c70d11445/devices/62687d6cb9f9fa4a4f9e3f17_OHOS_MPPT002/shadow"; //TODO：
        Map<String, String> paramsMap = new HashMap<String,String>();       //数据采用的哈希表结构
        Map<String, String> headerMap = new HashMap<String,String>();       //数据采用的哈希表结构
        // [{"key":"Content-Type","value":"application/json","description":"","type":"text","enabled":true}]
        headerMap.put("Content-Type", "application/json");//给map中添加元素
        headerMap.put("X-Auth-Token", "MIIWlAYJKoZ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QYWoQMAsGCWCGSAFlAwQCATANBgkqhkiG9w0BAQEFAASCAQB");//给map中添加元素


        // 发起get请求
        ZZRHttp.get(url,new ZZRCallBack.CallBackString() {
            @Override
            public void onFailure(int i, String s) {
                HiLog.info(TAG, "API返回失败");
            }
            @Override
            public void onResponse(String s) {
                HiLog.info(TAG, "API返回成功");
                try {
                    //1.调用fastjson解析，结果保存在JSON对应的类
                    OcMqttEntity ocmqttentity = JSON.parseObject(s,OcMqttEntity.class);

                    //这部分用来更新UI
                    ZSONObject zsonObject = new ZSONObject(); //首先，将要刷新的数据存放在一个ZSONObject实例中
                    //失败返回{"error_msg":"Incorrect IAM authentication information: x-auth-token not found","error_code":"APIG.0301","request_id":"483907208e6ce86b662ee9571d65f113"}
                    if(ocmqttentity.getDevice_id() != null) {
                        float InVoltage = ocmqttentity.getShadow().get(0).getReported().getProperties().getInVoltage() / 1000;
                        float OutVoltage = ocmqttentity.getShadow().get(0).getReported().getProperties().getOutVoltage() / 1000;
                        float InCurrent = ocmqttentity.getShadow().get(0).getReported().getProperties().getInCurrent();
                        float InPower = OutVoltage * InCurrent;
                        float efficiency = 98;

//                            zsonObject.put("service_id",ocmqttentity.getDevice_id());
                        zsonObject.put("InVoltage", InVoltage);
                        zsonObject.put("OutVoltage", OutVoltage);
                        zsonObject.put("InCurrent", InCurrent);
                        zsonObject.put("InPower", InPower);
                        zsonObject.put("efficiency", efficiency);
                    }
                    FormBindingData formBindingData = new FormBindingData(zsonObject); //3.将其封装在一个FormBindingData的实例中
                    try {
                        ((ControlMainAbility)context).updateForm(formId,formBindingData); //4.调用MainAbility的方法updateForm()，并将formBindingData作为第二个实参
                    } catch (FormException e) {
                        e.printStackTrace();
                        HiLog.info(TAG, "更新卡片失败");
                    }
                } catch (Exception e) {
                    HiLog.info(TAG, "解析失败");
                }
            }
        });
    }

    @Override
    public void onTriggerFormEvent(long formId, String message) {
        HiLog.info(TAG, "onTriggerFormEvent.");
    }

    @Override
    public Class<? extends AbilitySlice> getRoutePageSlice(Intent intent) {
        HiLog.info(TAG, "set route page slice.");
        ZSONObject zsonObject = ZSONObject.stringToZSON(intent.getStringParam("params"));
        if ("button".equals(zsonObject.getString("message"))) {
            return WidgetSlice.class;
        }
        return null;
    }


}
